<template>
  <div class="manageimage">
    <!-- 图片管理 -->
    <!-- 搜索框 -->
    <div class="search">
      <div class="box1">
        名称
        <el-input v-model="page.name" placeholder="请输入名称" maxlength="11"></el-input>
      </div>
      <div class="box2">
        筛选
        <el-cascader ref="cascaderQuery" :options="options" :props="optionProps" clearable @change="selectQuery" placeholder="请选择分类"></el-cascader>
      </div>
      <button @click="searchBtn">查询</button>
    </div>
    <!-- 页面内容 -->
    <div class="table">
      <div class="tableTitle">
        <div class="tableTitleName">图片列表</div>
        <div class="tableTitleBtn">
          <button class="delBtn" @click="delmore">批量删除</button>
          <button @click="addBoxBtn">上传</button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        border
        :header-cell-style="{
          textAlign: 'center',
          color: '#333',
          fontWeight: '400',
          fontSize: '14px',
          height: '45px',
          padding: '0px',
          margin: '0',
        }"
        style="width: 100%; margin: 0"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column label="序号" width="60">
          <template slot-scope="scope"
            ><input type="number" maxlength="7" v-model="scope.row.orderNum" @blur="editOrderNumber(scope.row)" style="width: 80%; text-align: center; border: none; outline: none"
          /></template>
        </el-table-column>
        <!-- <el-table-column label="编号">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column> -->
        <el-table-column prop="name" label="图片"
          ><template slot-scope="scope">
            <el-image style="width: 45px; height: 45px" :src="scope.row.url" fit="contain" :preview-src-list="srcList" @click="preview(scope.row.url)"></el-image></template
        ></el-table-column>
        <el-table-column label="名称"
          ><template slot-scope="scope"
            ><input type="text" maxlength="25" v-model="scope.row.name" @blur="editName(scope.row)" style="width: 90%; text-align: center; border: none; outline: none" /> </template
        ></el-table-column>
        <el-table-column label="分类" :show-overflow-tooltip="true">
          <template slot-scope="scope" v-if="scope.row.imageTypeId">
            <!-- <el-cascader
              v-model="scope.row.imageTypeId"
              :options="options"
              :props="optionProps"
              disabled

            ></el-cascader> -->
            <span>{{ scope.row.imageTypeName }}</span>
          </template></el-table-column
        >
        <el-table-column label="上传时间"
          ><template slot-scope="scope">{{ scope.row.createTime }} </template>
        </el-table-column>
        <el-table-column label="显示" width="70"
          ><template slot-scope="scope"><el-switch v-model="scope.row.isShow" active-color="#13ce76" inactive-color="#eee" @change="changeIsShow(scope.row)"> </el-switch> </template>
        </el-table-column>
        <el-table-column label="精选" width="70"
          ><template slot-scope="scope"><el-switch v-model="scope.row.level" active-color="#13ce66" inactive-color="#eee" @change="changeLevel(scope.row)"> </el-switch> </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <div v-if="scope.row">
              <span class="spanBtn" style="margin-right: 10px; cursor: pointer" @click="topBtn(scope.row)">置顶</span>
              <el-upload
                style="display: inline-block"
                ref="upload"
                action="https://wap.cyberxauto.com/api/image/update/upload"
                :headers="{ token: token }"
                :data="{
                  id: scope.row.id,
                }"
                :limit="1"
                :on-success="handleSuccess"
              >
                <span class="spanBtn" style="margin-right: 10px; cursor: pointer" slot="trigger">更换图片</span>
              </el-upload>
              <!-- <span class="spanBtn" style="margin-right: 40px; cursor: pointer" @click="editBtn(scope.row)">更换图片</span> -->
              <span class="spanBtn" style="cursor: pointer; margin-right: 10px" @click="delBtn(scope.row)">删除</span>
              <span class="spanBtn" style="cursor: pointer" @click="sortBtn(scope.row)">修改分类</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="tableData.length !== 0" style="text-align: center" class="pagbox">
        <el-pagination v-model="page" background layout="prev, pager, next" :total="total" :page-size="page.ps" :current-page="page.p" @current-change="handleCurrentChange"> </el-pagination>
      </div>
    </div>
    <!-- 图片上传组件 -->
    <uploadimg ref="uploadimg" @updateList="getlist"></uploadimg>
    <!-- 图片修改分类组件 -->
    <edit-sort ref="editSort" @update="getlist"></edit-sort>
  </div>
</template>

<script>
import uploadimg from './uploadimage.vue'
import editSort from './editSort.vue'
export default {
  name: 'manageimage',
  components: {
    uploadimg,
    editSort
  },
  data() {
    return {
      typeId: null, // 修改图片分类类型Id
      value1: 123, // 搜索级联选择器
      token: sessionStorage.getItem('token'),
      isResouceShow: 0,
      // 图片预览数组
      srcList: [],
      tableData: [], // 渲染列表数据
      tableDataCopy: [], // 修改时的复制列表数据
      page: {
        p: 1, // 分页页数
        ps: 8, // 分页条数
        name: null, // 模糊查询图片
        type: null // 模糊查询图片归属类型
      },
      total: null, // 总条数
      options: [], // 筛选列表数据
      // el-cascader显示字段修改
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        disabled: 'disabled'
      }
    }
  },
  created() {
    // 获取图片列表
    this.getlist()
    // 获取筛选列表
    this.getOptions()
  },
  methods: {
    // 修改分类
    sortBtn(val) {
      console.log('修改分类行信息', val)
      this.$refs.editSort.openCom(val)
    },
    // 修改名称
    editName(val) {
      console.log('修改名称信息', val)
      // 判断是否修改了信息
      this.tableDataCopy.forEach(item => {
        if (item.id === val.id && item.name !== val.name) {
          this.$confirm(`是否将名字修改为${val.name}？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            // 确认修改
            const changeRes = {
              id: val.id,
              name: val.name
            }
            const res = await this.$http.post('/image/update', changeRes)
            console.log('修改名称后台返回数据', res)
            if (res.data.code === 200) {
              this.$message({
                showClose: true,
                message: '修改名称成功',
                type: 'success'
              })
            } else {
              this.$message({
                showClose: true,
                message: '修改名称失败',
                type: 'warning'
              })
            }
          })
        }
      })
    },
    // 修改序号
    editOrderNumber(val) {
      console.log('修改名称信息', val)
      // 判断是否修改了信息
      this.tableDataCopy.forEach(item => {
        if (item.id === val.id && item.orderNum !== val.orderNum) {
          this.$confirm(`是否将序号修改为${val.orderNum}？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            // 确认修改
            const changeRes = {
              id: val.id,
              orderNum: val.orderNum
            }
            const res = await this.$http.post('/image/update', changeRes)
            console.log('修改序号后台返回数据', res)
            if (res.data.code === 200) {
              this.$message({
                showClose: true,
                message: '修改序号成功',
                type: 'success'
              })
              this.getlist()
            } else {
              this.$message({
                showClose: true,
                message: '修改序号失败',
                type: 'warning'
              })
            }
          })
        }
      })
    },
    // 点击预览图片
    preview(val) {
      this.srcList = []
      this.srcList.push(val)
    },
    // 修改显示状态
    async changeIsShow(value) {
      console.log(value)
      const changeRes = {
        id: value.id,
        isShow: value.isShow
      }
      const res = await this.$http.post('/image/update', changeRes)
      if (res.data.code !== 200) {
        this.$message({
          showClose: true,
          message: '修改显示状态失败',
          type: 'warning'
        })
      }
    },
    // 修改精选状态
    async changeLevel(value) {
      console.log(value)
      const changeRes = {
        id: value.id,
        level: value.level
      }
      const res = await this.$http.post('/image/update', changeRes)
      if (res.data.code !== 200) {
        this.$message({
          showClose: true,
          message: '修改精选状态失败',
          type: 'warning'
        })
      }
    },
    // 成功上传回调函数
    handleSuccess(res) {
      console.log(res, '122')
      if (res.code === 200) {
        this.$message({
          showClose: true,
          type: 'success',
          message: '修改图片成功'
        })
        this.getlist()
      } else {
        this.$message({
          showClose: true,
          type: 'error',
          message: '修改图片失败'
        })
      }
    },
    // 获取图片列表
    async getlist() {
      const res = await this.$http.get('/image/list', { params: { p: this.page.p, ps: this.page.ps, imageTypeId: this.page.type, name: this.page.name } })
      console.log('图片列表', res)
      if (res.data.code === 200) {
        this.tableData = res.data.data.imageList
        this.tableDataCopy = JSON.parse(JSON.stringify(res.data.data.imageList))
        this.total = res.data.data.count
        // this.tableData.forEach(item => {
        //   item.myData = [{ id: null }]
        //   item.myData[0].id = item.imageType.id
        //   console.log(item)
        // })
        console.log(this.tableData)
      }
    },
    // 获取筛选列表
    async getOptions() {
      const res = await this.$http.get('/image/type/list')
      console.log('分类列表', res)
      this.options = res.data.data
      this.options.unshift({
        id: 1,
        name: '全部'
      })
      this.options.forEach(item => {
        if (item.children) {
          item.children.unshift({
            id: 2,
            name: '全部'
          })
          item.children.forEach(itm => {
            if (itm.children) {
              itm.children.unshift({
                id: 3,
                name: '全部'
              })
            }
          })
        }
        // if (item.children.children) {
        //   item.children.children.unshift({
        //     id: 3,
        //     name: '全部'
        //   })
        // }
      })
      // 空数组去掉
      this.options = res.data.data || []

      for (const item of this.options || []) {
        if (!item.children || item.children.length === 0) {
          delete item.children
          // item.disabled = 'disabled'
        } else {
          this.deepArr(item.children)
        }
      }
    },

    deepArr(data) {
      for (const item of data || []) {
        if (!item.children || item.children.length === 0) {
          delete item.children
        } else {
          this.deepArr(item.children)
        }
      }
    },
    // 翻页
    handleCurrentChange(currentPage) {
      this.page.p = currentPage
      this.getlist()
    },
    // 筛选时的节点信息
    selectQuery() {
      // console.log('筛选节点信息', this.$refs.cascaderQuery.getCheckedNodes()[0].data)
      // console.log('筛选长度', this.$refs.cascaderQuery)
      // if (this.$refs.cascaderQuery.checkedValue.length === 0) {
      //   this.page.type = null
      // } else {
      //   const id = this.$refs.cascaderQuery.getCheckedNodes()[0].data.id
      //   this.page.type = id
      // }
      console.log('筛选长度', this.$refs.cascaderQuery.getCheckedNodes())
      if (this.$refs.cascaderQuery.getCheckedNodes()[0]) {
        if (this.$refs.cascaderQuery.getCheckedNodes()[0].data.id === 1) {
          this.page.type = null
        } else if (this.$refs.cascaderQuery.getCheckedNodes()[0].data.id === 2) {
          this.page.type = this.$refs.cascaderQuery.getCheckedNodes()[0].parent.value
        } else if (this.$refs.cascaderQuery.getCheckedNodes()[0].data.id === 3) {
          this.page.type = this.$refs.cascaderQuery.getCheckedNodes()[0].parent.value
        } else {
          this.page.type = this.$refs.cascaderQuery.getCheckedNodes()[0].data.id
        }
      }
      // if (this.$refs.cascaderQuery.getCheckedNodes()[0]) {
      //   const id = this.$refs.cascaderQuery.getCheckedNodes()[0].data.id
      //   this.page.type = id
      // } else {
      //   this.page.type = null
      // }
      console.log(this.page.type)
    },
    // 清空筛选
    clear() {
      this.$refs.cascaderQuery.checkedValue = ''
      this.$refs.cascaderQuery.$refs.panel.activePath = []
      this.$refs.cascaderQuery.$refs.panel.syncActivePath()
    },
    // 查询按钮
    async searchBtn() {
      console.log('查询')
      const res = await this.$http.get('/image/list', { params: { p: 1, ps: this.page.ps, imageTypeId: this.page.type, name: this.page.name } })
      console.log('搜索查询后台返回信息', res)
      if (res.data.code === 200) {
        this.$message({
          showClose: true,
          type: 'success',
          message: '查询成功！'
        })
        this.tableData = res.data.data.imageList
        this.tableDataCopy = JSON.parse(JSON.stringify(res.data.data.imageList))
        this.total = res.data.data.count
      }
    },
    // 图片分类类型修改
    // handleChange(val) {
    //   console.log('类型修改', val)
    //   this.typeId = val[val.length - 1]
    //   this.$forceUpdate()
    //   console.log('反转数组', this.typeId)
    // },
    // 图片修改类型失焦
    async changeType(val) {
      console.log('shijiao ', val)
      const changeRes = {
        id: val.id,
        imageTypeId: this.typeId
      }
      const res = await this.$http.post('/image/update', changeRes)
      console.log(res)
      if (res.data.code === 200) {
        this.$message({
          showClose: true,
          type: 'success',
          message: '修改成功'
        })
        this.showdialog = false
        this.$emit('update')
      } else {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '修改失败'
        })
      }
    },

    // 添加按钮
    addBoxBtn() {
      console.log('添加')
      this.$refs.uploadimg.openCom()
    },
    // 置顶按钮
    async topBtn(val) {
      console.log('置顶')
      this.$confirm('确认置顶这张图片', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // const delsingle = { id: val.id }

        const res = await this.$http.post('/image/topping?id=' + val.id)
        console.log('置顶返回信息', res)
        if (res.data.code === 200) {
          this.$message({
            showClose: true,
            type: 'success',
            message: '置顶成功'
          })
          this.getlist()
        } else {
          this.$message.error('置顶失败')
        }
      }).catch(
        () => {
          this.$message({
            showClose: true,
            type: 'info',
            message: '已取消置顶'
          })
        })
    },
    // 编辑图片按钮
    editBtn() {
      console.log('编辑')
    }, // 删除按钮
    async delBtn(val) {
      console.log('删除', val.id)
      const delsingle = []
      this.$confirm('确认删除这张图片', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        delsingle.push(val.id)
        // 判断是否是唯一一个数据
        if (delsingle.length === this.tableData.length) {
          const res = await this.$http.delete('/image', { data: delsingle })
          console.log('删除返回信息', res)
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功'
            })
            if (this.page.p === 1) {
              this.page.p = 1
            } else {
              this.page.p = this.page.p - 1
            }
            this.getlist()
          } else {
            this.$message.error('删除失败')
          }
        } else {
          const res = await this.$http.delete('/image', { data: delsingle })
          console.log('删除返回信息', res)
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功'
            })
            this.getlist()
          } else {
            this.$message.error('删除失败')
          }
        }
      }).catch(
        () => {
          this.$message({
            showClose: true,
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除按钮
    async delmore() {
      console.log('批量删除')
      const delarr = []
      this.$confirm('确认批量删除图片?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.multipleSelection.forEach(item => {
          delarr.push(item.id)
        })
        // 如果删除全部返回上一页
        if (delarr.length === this.tableData.length) {
          const res = await this.$http.delete('/image', { data: delarr })
          console.log('批量删除后台返回信息', res)
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功！'
            })
            if (this.page.p === 1) {
              this.page.p = 1
            } else {
              this.page.p = this.page.p - 1
            }

            this.getlist()
            // 未全部删除
          } else {
            this.$message.error('删除失败')
          }
        } else {
          const res = await this.$http.delete('/image', { data: delarr })
          console.log('批量删除后台返回信息', res)
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功！'
            })
            this.getlist()
          } else {
            this.$message.error('删除失败')
          }
        }
      }).catch(
        () => {
          this.$message({
            showClose: true,
            type: 'info',
            message: '删除失败或未选择图片'
          })
        })
    },
    // 多选图片事件
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log('多选', val)
    }
  }
}
</script>
<style>
body,
html,
#app {
  min-width: 1100px !important;
}
</style>
<style lang="less" scoped>
.manageimage {
  padding: 15px 20px;
  .search {
    width: 100%;
    height: 50px;
    display: flex;
    background-color: #fff;
    box-sizing: border-box;
    .box1 {
      font-size: 14px;
      color: #555;
      margin-right: 30px;
      /deep/ .el-input {
        width: 140px;
        height: 30px;
        border-radius: 15px;
        .el-input__inner {
          width: 140px;
          height: 30px;
          border-radius: 15px;
        }
      }
    }
    .box2 {
      font-size: 14px;
      color: #555;
      margin-right: 30px;
      /deep/.el-cascader {
        width: 250px;

        line-height: 30px;
        .el-input .el-input__inner {
          border-radius: 30px !important;
          height: 30px !important;
          line-height: 30px !important;
        }
      }
      .el-select {
        width: 110px;
        height: 30px;
        /deep/ .el-input {
          width: 110px;
          height: 30px;
          line-height: 30px;
          border-radius: 15px;
          .el-input__inner {
            width: 110px;
            height: 30px;
            border-radius: 15px;
          }
        }
      }
    }
    button {
      cursor: pointer;
      box-sizing: border-box;
      font-size: 16px;
      color: #ffffff;
      width: 90px;
      height: 30px;
      background: #333333;
      border-radius: 18px;
    }
  }
  .table {
    background-color: #fff;
    .tableTitle {
      position: relative;
      height: 50px;
      line-height: 50px;
      background-color: #eee;
      .tableTitleName {
        font-size: 16px;
        color: #333;
        margin-left: 20px;
      }
      .tableTitleBtn {
        position: absolute;
        top: 0;
        right: 25px;
        button {
          cursor: pointer;
          width: 80px;
          height: 30px;
          border-radius: 15px;
          font-size: 16px;
          color: #333;
          margin-left: 15px;
        }
        .delBtn {
          width: 105px;
        }
      }
    }
  }
  // 隐藏上传文件列表
  /deep/.el-upload-list {
    display: none;
  }
  // 清除input数字按钮按钮
  /deep/ input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
  // 修改级联选择器箭头行高
  /deep/.el-input__icon {
    line-height: 30px !important;
  }
  // 翻页按钮样式修改
  .pagbox {
    /deep/.el-pagination.is-background .el-pager li:not(.disabled).active {
      background-color: #333;
    }
  }
  // 修改行高
  /deep/.el-table td {
    padding: 0;
  }
  // 修改图片预览时的关闭按钮颜色和位置
  /deep/.el-image-viewer__wrapper .el-icon-circle-close:before {
    color: #fff;
  }
  /deep/.el-image-viewer__wrapper .el-image-viewer__close {
    top: 10%;
    right: 5%;
  }
}
</style>
